<?php
/**
 * Created by PhpStorm.
 * User: HeiYanHeiMao
 * Date: 2020/2/23
 * Time: 11:22
 */

namespace app\controller;

use app\BaseController;
use app\middleware\Check;
use app\model\StoreModel;
use app\Request;
use think\facade\Db;
use think\facade\Validate;
use think\response\Json;
use think\validate\ValidateRule;
use think\facade\Cache;

require_once '../sdk/WxpayAPI/lib/WxSend.Api.php';
require_once '../sdk/API-PHP/API_PHP_DEMO.php';

/** 商户管理
 * Class Store
 * @package app\controller
 */
class Store extends BaseController
{
    protected $middleware = [Check::class];

    /**经营范围列表
     * @param Request $request
     * @return Json
     */
    public function scope_list(Request $request)
    {
        if (!$request->isPost()) return jsonFail('非法请求方式');
        $data = Db::table('eb_scope')->select()->toArray();
        return jsonSuccess('获取成功', $data);
    }

    /**商户信息
     * @param Request $request
     * @return Json
     */
    public function store_info(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $store = Store_find($token);
        unset($store['pwd']);
        return jsonSuccess('获取成功', $store);
    }

    /**商户注册
     * @param Request $request
     * @return Json
     */
    public function register(Request $request)
    {
        if (!$request->isPost()) return jsonFail('非法请求方式');
        // 接收参数
//        $input['account'] = $request->post('account'); // 商户账号
        $input['pwd'] = $request->post('pwd'); // 商户密码
        $input['repwd'] = $request->post('repwd'); // 商户再次密码
        $input['company_name'] = $request->post('company_name'); // 单位名称
        $input['legal_name'] = $request->post('legal_name'); // 法人名字
        $input['address'] = $request->post('address'); // 地址
        $input['scope_ids'] = $request->post('scope_ids'); // 经营范围ids
        $input['cert_validity'] = $request->post('cert_validity'); // 经营有效期
        $input['cert_pic'] = $request->post('cert_pic'); // 营业执照照片
        $input['allow_pic'] = $request->post('allow_pic'); // 经营许可证件照
        $input['logo'] = $request->post('logo'); // 商铺logo
        $input['shop_name'] = $request->post('shop_name'); // 商铺名称
        $input['time_interval'] = $request->post('time_interval');  //营业时间
        $input['send_range'] = $request->post('send_range');  //配送时间段
        $input['school_ids'] = $request->post('school_ids'); // 可配送学校
        $input['bank_no'] = $request->post('bank_no', ''); // 银行卡号
        $input['bank_address'] = $request->post('bank_address', ''); // 开户行
        $input['bank_phone'] = $request->post('bank_phone'); // 银行预留电话
        $input['bank_name'] = $request->post('bank_name', ''); // 银行预留姓名
//        $input['sn'] = $request->post('sn'); // 打印机编号
        //验证参数
        $validate = Validate::rule([
//            'account' => ValidateRule::isRequire(null, '缺少参数'),
            'pwd' => ValidateRule::isRequire(null, '缺少参数'),
            'repwd' => function ($value, $all) {
                return $value == $all['pwd'] ? true : '两次密码输入不一致';
            },
            'company_name' => ValidateRule::isRequire(null, '缺少参数1'),
            'legal_name' => ValidateRule::isRequire(null, '缺少参数2'),
            'address' => ValidateRule::isRequire(null, '缺少参数3'),
            'scope_ids' => ValidateRule::isRequire(null, '缺少参数4'),
            'cert_validity' => ValidateRule::isRequire(null, '缺少参数5'),
            'cert_pic' => ValidateRule::isRequire(null, '缺少参数6'),
            'allow_pic' => ValidateRule::isRequire(null, '缺少参数7'),
            'logo' => ValidateRule::isRequire(null, '缺少参数8'),
            'shop_name' => ValidateRule::isRequire(null, '缺少参数9'),
            'time_interval' => ValidateRule::isRequire(null, '缺少参数10'),
            'send_range' => ValidateRule::isRequire(null, '缺少参数11'),
            'school_ids' => ValidateRule::isRequire(null, '缺少参数12'),
//            'bank_address' => ValidateRule::isRequire(null, '缺少参数14'),
            'bank_phone' => ValidateRule::isRequire(null, '缺少参数15'),
//            'bank_name' => ValidateRule::isRequire(null, '缺少参数16'),
//            'sn' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return StoreModel::register($input);
    }

    /**商户登录
     * @param Request $request
     * @return Json
     */
    public function login(Request $request)
    {
        if (!$request->isPost()) return jsonFail('非法请求方式');
        // 接收参数
        $input['phone'] = $request->post('phone'); // 商户账号
        $input['pwd'] = $request->post('pwd'); // 商户密码
        //验证参数
        $validate = Validate::rule([
            'phone' => ValidateRule::isRequire(null, '缺少参数'),
            'pwd' => ValidateRule::isRequire(null, '缺少参数')
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return StoreModel::login($input);
    }

    /**商户接单
     * @param Request $request
     * @return Json
     */
    public function receiveOrder(Request $request)
    {
        if (!$request->isPost()) return jsonFail('非法请求方式');
        // 接收参数
        $input['id'] = $request->post('id'); // 订单id
        //验证参数
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数')
        ]);
        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return StoreModel::receiveOrder($input, $request->param('token'));
    }

    /**获取商户下商品和分类
     * @param Request $request
     * @return Json
     */
    public function goods_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $store = Store_find($token);
        $goods_list = Db::table('eb_category')->select()->toArray();
        $Ids = array_column($goods_list, 'id');
        $goods = Db::table('eb_goods')->where('store_id', $store['id'])->where('cate_id', 'in', $Ids)->select()->toArray();
        foreach ($goods as $otherInfo) {
            $key = array_search($otherInfo['cate_id'], $Ids);
            $goods_list[$key]['goods'][] = $otherInfo;
        }
        return jsonSuccess('获取成功', $goods_list);
    }

    /**修改商品信息
     * @param Request $request
     * @return Json
     */
    public function edit_goods(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');//token
        $goods_id = $request->param('goods_id');//商品ID
        $store = Store_find($token);
        $name = $request->param('name');//name
        $pic = $request->param('pic');//pic
        $price = abs($request->param('price'));//price
        $detail = $request->param('detail');//detail
        $stock = intval(abs($request->param('stock')));//库存
        $input['meat_num'] = abs($request->post('meat_num', 0)); // 荤菜个数
        $input['veg_num'] = abs($request->post('veg_num', 0)); // 素菜个数
        $input['type'] = $request->post('type', 1); // 1 普通类型 2套餐类型
        if ($input['type'] == 2 && ($input['meat_num'] == 0 || $input['veg_num'] == 0)) return jsonFail('商品为套餐时，个数不能为0喔');
        try {
            Db::startTrans();
            $res = Db::table('eb_goods')->where('id', $goods_id)->where('store_id', $store['id'])->update([
                'name' => $name,
                'pic' => $pic,
                'price' => $price,
                'detail' => $detail,
                'stock' => $stock,
                'type' => $input['type'],
                'meat_num' => $input['meat_num'],
                'veg_num' => $input['veg_num'],
            ]);
            if ($res != 0) {
                $data = [
                    'id' => $goods_id,
                    'type' => $input['type'],
                    'meat_num' => $input['meat_num'],
                    'veg_num' => $input['veg_num'],
                    'name' => $name,
                    'price' => $price,
                    'stock' => $stock,
                ];
                $editRtn = Cache::store('redis')->handler()->hMSet('dxsd-goods-' . $goods_id, $data);
                if ($editRtn === true) {
                    Db::commit();
                    return jsonSuccess('修改成功！');
                } else {
                    Db::rollback();
                    return jsonFail('修改失败！');
                }
            } else {
                Db::rollback();
                return jsonFail('修改失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }
    }

    /**修改商户信息
     * @param Request $request
     * @return Json
     */
    public function edit_store(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $store = Store_find($token);
//        $input['account'] = $request->post('account'); // 单位名称
        $input['company_name'] = $request->post('company_name'); // 单位名称
        $input['legal_name'] = $request->post('legal_name'); // 法人名字
        $input['address'] = $request->post('address'); // 地址
        $input['scope_ids'] = $request->post('scope_ids'); // 经营范围ids
        $input['cert_validity'] = $request->post('cert_validity'); // 经营有效期
        $input['cert_pic'] = $request->post('cert_pic'); // 营业执照照片
        $input['allow_pic'] = $request->post('allow_pic'); // 经营许可证件照
        $input['logo'] = $request->post('logo'); // 商铺logo
        $input['time_interval'] = $request->post('time_interval');  //营业时间
        $input['send_range'] = $request->post('send_range');  //配送时间段
        $input['bank_no'] = $request->post('bank_no'); // 银行卡号
        $input['bank_address'] = $request->post('bank_address'); // 开户行
        $input['bank_phone'] = $request->post('bank_phone'); // 银行预留电话
        $input['bank_name'] = $request->post('bank_name'); // 银行预留姓名
        //验证参数
        $validate = Validate::rule([
//            'account' => ValidateRule::isRequire(null, '缺少参数'),
            'company_name' => ValidateRule::isRequire(null, '缺少参数'),
            'legal_name' => ValidateRule::isRequire(null, '缺少参数'),
            'address' => ValidateRule::isRequire(null, '缺少参数'),
            'scope_ids' => ValidateRule::isRequire(null, '缺少参数'),
            'cert_validity' => ValidateRule::isRequire(null, '缺少参数'),
            'cert_pic' => ValidateRule::isRequire(null, '缺少参数'),
            'allow_pic' => ValidateRule::isRequire(null, '缺少参数'),
            'logo' => ValidateRule::isRequire(null, '缺少参数'),
            'time_interval' => ValidateRule::isRequire(null, '缺少参数'),
            'send_range' => ValidateRule::isRequire(null, '缺少参数'),
            'bank_no' => ValidateRule::isRequire(null, '缺少参数'),
            'bank_address' => ValidateRule::isRequire(null, '缺少参数'),
            'bank_phone' => ValidateRule::isRequire(null, '缺少参数'),
            'bank_name' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return StoreModel::edit($input, $store['id']);
    }

    /**修改营业状态
     * @param Request $request
     * @return Json
     */
    public function business_status(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $status = $this->request->param('status');//status
        $store = Store_find($token);
        if (is_null($status)) return jsonFail('缺少参数');
        if ($status != 0 && $status != 1) return jsonFail('参数错误');
        try {
            $res = Db::table('eb_store')->where('id', $store['id'])->update(['is_open' => $status]);
            if ($res != 0) return jsonSuccess('修改成功');
            return jsonFail('修改失败');
        } catch (\Exception $e) {
            return jsonFail('系统错误~');
        }
    }

    /**修改商铺基本信息
     * @param Request $request
     * @return Json
     */
    public function edit_basic(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $shop_name = $this->request->param('shop_name');//shop_name
        $logo = $this->request->param('logo');//logo
        $send_start = $this->request->param('send_start');//send_start
        $send_end = $this->request->param('send_end');//send_end
        $describe = $this->request->param('describe');//describe
        $time_interval = $request->post('time_interval');  //营业时间
        $send_range = $request->post('send_range');  //配送时间段
        $store = Store_find($token);
        if (empty($shop_name) || empty($logo) || empty($describe) || empty($send_range) || empty($time_interval)) return jsonFail('缺少参数');
        try {
            $res = Db::table('eb_store')->where('id', $store['id'])->update([
                'shop_name' => $shop_name,
                'logo' => $logo,
                'describe' => $describe,
                'time_interval' => $time_interval,
                'send_range' => $send_range,
            ]);
            if ($res != 0) {
                $data = [
                    'id' => $store['id'],
                    'time_interval' => $time_interval,//营业时间
                    'send_range' => $send_range,//配送时间
                    'shop_name' => $shop_name,
                    'bank_phone' => $store['bank_phone'],
                ];
                $editRtn = Cache::store('redis')->handler()->hMSet('dxsd-store-' . $store['id'], $data);
                if ($editRtn === true) {
                    Db::commit();
                    return jsonSuccess('编辑成功！');
                } else {
                    Db::rollback();
                    return jsonFail('编辑失败！');
                }
            }
        } catch (\Exception $e) {
            return jsonFail('服务器内部错误~');
        }
    }

    /**商家拒绝退款
     * @param Request $request
     * @return Json
     */
    public function Refuse_money(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $order_no = $this->request->param('order_no');//订单号
        $unback_reason = $this->request->param('unback_reason');//拒绝退款原因
        if (empty($unback_reason) || empty($order_no)) return jsonFail('缺少参数');
        $order = Db::table('eb_order')->where('order_no', $order_no)->find();
        try {
            $res = Db::table('eb_order')->where('order_no', $order_no)->update(['unback_reason' => $unback_reason, 'status' => 2, 'is_refues' => 1]);
            $send = new \WxSendApi();
            $ds = json_decode($send->send_Template_Refuse($order['user_id'], $order), true); //转为数组;
            if ($res != 0 && $ds['errcode'] == 0) return jsonSuccess('操作成功');
            return jsonFail('操作失败');
        } catch (\Exception $e) {
            return jsonFail('系统错误~');
        }
    }

    /** 商户添加打印机
     * @param Request $request
     */
    public function add_printer(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');//token
        $status = $request->param('status');//状态
        $store = Store_find($token);
        $sn = $request->param('sn');//sn
        $key = $request->param('key');//key
        if (empty($sn) || empty($key) || empty($status)) return jsonFail('缺少参数');
        try {
            Db::startTrans();
            $sn_data = $store;
            $send = new \API_PHP_DEMO();
            $printerContent = $sn . '#' . $key . '#' . $store['shop_name'] . $sn . '#';
            $code = $send->printerAddlist($printerContent);
            $data = json_decode($code, true);
            $printr = ['sn' => $sn, 'key' => $key, 'status' => $status, 'count' => 0];//status 1:正常 2：禁用
            if (!empty($data['data']['ok'])) {
                if (!empty($sn_data['sn'])) {
                    $printr_data = json_decode($sn_data['sn'], true);
                    $leng = count($printr_data);//打印机长度
                    $lengs = array_push($printr_data, $printr);
                    if ($leng == $lengs) return jsonFail('追加异常');
                } else {
                    $printr_data = [$printr];
                }
                $addRtn = Cache::store('redis')->handler()->hSet('dxsd-store-' . $store['id'], 'sn', json_encode($printr_data));
                $sites = array('0', '1');
                if (in_array($addRtn, $sites)) {
                    $res = Db::table('eb_store')->where('id', $store['id'])->update(['sn' => json_encode($printr_data)]);
                    if ($res != 0) {
                        Db::commit();
                        return jsonSuccess('添加打印机成功！', $data);
                    } else {
                        Db::rollback();
                        return jsonFail('系统错误~', $res);
                    }
                } else {
                    Db::rollback();
                    return jsonFail('系统错误~', $addRtn);
                }
            } else {
                Db::rollback();
                return jsonFail('添加失败', $data);
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail('系统错误~', $e->getMessage());
        }
    }

    /** 商户打印机列表
     * @param Request $request
     */
    public function prints_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');//token
        $store = Store_find($token);
        return jsonSuccess('获取成功', json_decode($store['sn'], true));
    }

    /** 商户测试打印机
     * @param Request $request
     */
    public function test_print(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $sn = $request->param('sn');//sn
        $send = new \API_PHP_DEMO();
        $arr[0] = array('title' => '打印机编号：' . $sn, 'price' => '1', 'num' => '1');
        $arr[1] = array('title' => '可乐鸡翅+蒜蓉蒸扇贝', 'price' => '10.3', 'num' => '6');
        $arr[2] = array('title' => '紫苏焖鹅+梅菜肉饼+椒盐虾+北京烤鸭', 'price' => '10.0', 'num' => '8');
        $data = test_prints($arr, 14, 6, 3, 6);
        $code = $send->printMsg($sn, $data, 1);
        $data = json_decode($code, true);
        if ($data['ret'] == 0) return jsonSuccess('正在打印,请留意打印机是否开机联网');
        return jsonFail('测试失败，请联系管理员', $data);
    }

    /** 商户再次打印订单
     * @param Request $request
     */
    public function again_print(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $sn = $request->param('sn');//sn
        $order = $request->param('order');//订单号
        $token = $request->param('token');//token
        $store = Store_find($token);
        $send = new \API_PHP_DEMO();
        try {
            $field = 'a.is_raised,a.floor_id,a.dormitory_id,a.id,a.store_id,a.order_no,a.remark,a.floor_price,a.delivery_price,a.total_price,a.code,a.create_time,b.name,b.phone,b.address,c.name as dormitory_name,d.name as floor_name,e.name as school_name,e.type';
            $order_info = Db::table('eb_order')->alias('a')
                ->join('eb_user_address b', 'a.address_id = b.id')
                ->join('eb_dormitory c', 'b.dormitory_id = c.id')
                ->join('eb_floor d', 'b.floor_id = d.id')
                ->join('eb_school e', 'a.school_id = e.id')
                ->where('a.order_no', $order)
                ->field($field)
                ->find();
            $order_list = Db::table('eb_order_detail')->alias('a')
                ->leftJoin('eb_goods b', 'a.goods_id = b.id')
                ->where('a.order_id', $order_info['id'])
                ->field('a.*,b.*')
                ->select()->toArray();
            $data = combination($store, $order_info, $order_list, 14, 6, 3, 6, 2);
            $code = $send->printMsg($sn, $data, 1);
            $data = json_decode($code, true);
            if ($data['ret'] == 0) return jsonSuccess('打印成功');
            return jsonFail('再次打印失败', $data);
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }

    /** 商户删除打印机
     * @param Request $request
     */
    public function Delprintr(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');//token
        $sn = $request->param('sn');//sn
        $store = Store_find($token);
        $send = new \API_PHP_DEMO();
        $sn_data = json_decode($store['sn'], true);
        $code = $send->printerDelList($sn);
        $data = json_decode($code, true);
        if (!empty($data['data']['ok'])) {
            foreach ($sn_data as $key => $value) {
                if ($value['sn'] == $sn) {
                    unset($sn_data[$key]);
                }
            }
            Db::startTrans();
            $addRtn = Cache::store('redis')->handler()->hSet('dxsd-store-' . $store['id'], 'sn', json_encode($sn_data));
            if ($addRtn === 0) {
                $res = Db::table('eb_store')->where('id', $store['id'])->update(['sn' => json_encode($sn_data)]);
                Db::commit();
                return jsonSuccess('修改打印机状态成功！', $res);
            } else {
                Db::rollback();
                return jsonFail('系统错误~', $data);
            }
        } else {
            return jsonFail('删除打印机出错', $data);
        }
    }

    /** 商户修改打印机状态
     * @param Request $request
     */
    public function printr_status(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');//token
        $sn = $request->param('sn');//sn
        $status = $request->param('status');//status 1:正常 2：禁用
        $store = Store_find($token);
        $sn_data = json_decode($store['sn'], true);
        foreach ($sn_data as $key => &$value) {
            if ($value['sn'] == $sn) {
                $value['status'] = $status;
            }
        }
        try {
            Db::startTrans();
            $addRtn = Cache::store('redis')->handler()->hSet('dxsd-store-' . $store['id'], 'sn', json_encode($sn_data));
            if ($addRtn === 0) {
                $res = Db::table('eb_store')->where('id', $store['id'])->update(['sn' => json_encode($sn_data)]);
                Db::commit();
                return jsonSuccess('修改打印机状态成功！', $res);
            } else {
                Db::rollback();
                return jsonFail('系统错误~', $addRtn);
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }

    }

    /** 每日流水
     * @param Request $request
     */
    public function report(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');//token
        $store = Store_find($token);
        $start_time = $request->param('start_time');//开始时间
        $end_time = $request->param('end_time');//结束时间
        $status = $request->param('status');//订单状态
        $financial_status = $request->param('financial_status');//结算状态状态 0:未结算 1：已结算 2：全部
        if (empty($start_time) || empty($end_time) || is_null($status) || is_null($financial_status)) return jsonFail('缺少参数');
        $arr = explode(',', $status);
        switch ($financial_status) {
            case 0://
                $data['list'] = Db::table('eb_order')->where('store_id', $store['id'])->where('is_pay', 1)->where('financial_status', $financial_status)->where('status', 'in', $arr)->whereTime('create_time', 'between', [$start_time, $end_time])->field('order_no,store_price,code,create_time')->select()->toArray();
                break;
            case 1:
                $data['list'] = Db::table('eb_order')->where('store_id', $store['id'])->where('is_pay', 1)->where('financial_status', $financial_status)->where('status', 'in', $arr)->whereTime('create_time', 'between', [$start_time, $end_time])->field('order_no,store_price,code,create_time')->select()->toArray();
                break;
            case  2:
                $data['list'] = Db::table('eb_order')->where('store_id', $store['id'])->where('is_pay', 1)->where('status', 'in', $arr)->whereTime('create_time', 'between', [$start_time, $end_time])->field('order_no,store_price,code,create_time')->select()->toArray();
                break;
        }
        $data['financial_money_1'] = Db::table('eb_order')->where('store_id', $store['id'])->where('is_pay', 1)->where('status', '>=', 4)->where('financial_status', 1)->sum('store_price');
        $data['financial_money_0'] = Db::table('eb_order')->where('store_id', $store['id'])->where('is_pay', 1)->where('status', '>=', 4)->where('financial_status', 0)->sum('store_price');
        $data['financial_num_1'] = Db::table('eb_order')->where('store_id', $store['id'])->where('is_pay', 1)->where('status', '>=', 4)->where('financial_status', 1)->count();
        $data['financial_num_0'] = Db::table('eb_order')->where('store_id', $store['id'])->where('is_pay', 1)->where('status', '>=', 4)->where('financial_status', 0)->count();
        return jsonSuccess('获取成功', $data);
    }

    /**获取所有分类
     * @param Request $request
     * @return Json
     */
    public function category_list(Request $request)
    {
        $cate_list = Db::table('eb_category')->order('sort')->select()->toArray();
        return jsonSuccess('获取成功', $cate_list);
    }

    /**获取该分类下商品
     * @param Request $request
     * @return Json
     */
    public function cateid_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $cate_id = $this->request->param('cate_id');//分类ID
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $school_id = $this->request->param('school_id');
        $dormitory_id = $this->request->param('dormitory_id');//宿舍楼ID
        if (empty($cate_id) || empty($school_id)) return jsonFail('缺少参数');
        $eb_school_store = Db::table('eb_school_store')->where('school_id', $school_id)->select()->toArray();
        $storeIDs = array_column($eb_school_store, 'store_id');//商家ID集合
        $store = Db::table('eb_store')->where('id', 'in', $storeIDs)->whereLike('dor_ids', '%,' . $dormitory_id . ',%')->where('status', 1)->field('is_open,id,shop_name,logo,score,is_open')->select()->toArray();
        foreach ($store as $key => $value) {
            $store[$key]['goods'] = Db::table('eb_goods')->where('is_show', 1)->where('cate_id', $cate_id)->where('store_id', $value['id'])->page($page, $limit)->select()->toArray();
            if (empty($store[$key]['goods'])) {
                unset($store[$key]['goods']);
                unset($store[$key]);
            }
        }
        return jsonSuccess('获取成功', $store);
    }

    /**修改商品是否售罄
     * @param Request $request
     * @return Json
     */
    public function goods_out(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $goods_id = $this->request->param('goods_id');//商品ID
        $is_out = $this->request->param('is_out');//0:正常 1：售罄
        if (is_null($is_out)) return jsonFail('缺少参数');
        $store = Store_find($token);
        try {
            $res = Db::table('eb_goods')->where('id', $goods_id)->where('store_id', $store['id'])->update([
                'is_out' => $is_out,
            ]);
            if ($res != 0) return jsonSuccess('修改成功');
            return jsonFail('修改失败');
        } catch (\Exception $e) {
            return jsonFail('系统错误~');
        }
    }

    /**修改商品是否上架
     * @param Request $request
     * @return Json
     */
    public function goods_show(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
        $goods_id = $this->request->param('goods_id');//商品ID
        $is_show = $this->request->param('is_show');//1:正常 0：下架
        if (is_null($is_show)) return jsonFail('缺少参数');
        $store = Store_find($token);
        try {
            $res = Db::table('eb_goods')->where('id', $goods_id)->where('store_id', $store['id'])->update([
                'is_show' => $is_show,
            ]);
            if ($res != 0) return jsonSuccess('修改成功');
            return jsonFail('修改失败');
        } catch (\Exception $e) {
            return jsonFail('系统错误~');
        }
    }

    /**修改是否可以退款
     * @param Request $request
     * @return Json
     */
    public function is_refuse(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $this->request->param('token');//token
//        $goods_id = $this->request->param('goods_id');//商品ID
        $is_refues = $this->request->param('is_refues');//0:可退款 1：不可退
        if (is_null($is_refues)) return jsonFail('缺少参数');
        $store = Store_find($token);
        try {
            $res = Db::table('eb_store')->where('id', $store['id'])->update([
                'is_refues' => $is_refues,
            ]);
            if ($res != 0) return jsonSuccess('修改成功');
            return jsonFail('修改失败');
        } catch (\Exception $e) {
            return jsonFail('系统错误~');
        }
    }

    public function tests(Request $request)
    {
        $token = $request->param('token');//token
//        $store = Store_find($token);
//        $data = json_decode($store['sn'],true);
//        $new_sndata = $data;
//        foreach ($data as $key=>$value){
//            if($value['status']==2) unset($data[$key]);
//        }
//        $last_data = array_column($data, 'count', 'sn');
//        $pos = array_search(min($last_data), $last_data);
//       var_dump($pos);
//        echo $a[$pos]; //99
//        $money = 2;
//        $fuwu = 0;
//        $delivery = 0;
//        $school = Cache::store('redis')->handler()->hGet('dxsd-school-' . 1,'delivery');
//        $one = explode(',',$school);
//        foreach ($one as $key=>$value){
//            $value = explode('-',$value);
//                if($key==0 && $money<$value[0]) return jsonFail('订单'.$value[0].'起送');
//                if($key==0 && $money>=$value[0]&&$money <=$value[1]){//第一次
//                    $fuwu = $value[2];//服务费
//                    $delivery = $value[3];//配送费
//                    break;
//                }
//                if($money>$value[0]&&$money <=$value[1]){
//                    $fuwu = $value[2];//服务费
//                    $delivery = $value[3];//配送费
//                    break;
//                }
//        }
//        $manag = [];
//        for ($i = 0; $i <= 4; $i++) {
//            if (!in_array(1, $manag)) {
//                $lengs = array_push($manag, 1);
//            }
//        }

//        var_dump($fuwu);
//        var_dump($delivery);
    }

}